
package com.example.timethread;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Timer;

public class MainActivity extends AppCompatActivity {

    public static final int start = 10000;
    public static final int wait = 10001;
    public static final int stop = 10002;
    public static final int reset = 10003;

    int num;
    int num_wait;

    int flag = 0;    //用于判断是使用num还是num_wait
    int f_wait = 0;  //用于暂停线程
    int f_reset =0;

    private TextView textView;
    private EditText editText;
    private ProgressBar progressBar;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case start:
                    if (flag == 0) {
                        textView.setText(String.valueOf(num));
                        num--;
                    } else if (flag == 1) {
                        //TODO 点击暂停后再点开始会直接减1，需处理
                        textView.setText(String.valueOf(num_wait-1));
                        num_wait--;
                    }else if(flag ==2){
                        textView.setText("");
                      //  editText.setText("");
                    }
                    break;
                case wait:
                    textView.setText(String.valueOf(num_wait));
                    break;



                default:
                    break;
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //绑定UI组件
        setContentView(R.layout.activity_main);



        editText = (EditText) findViewById(R.id.edit);
        textView = (TextView) findViewById(R.id.text);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);
        Button btnStart = (Button) findViewById(R.id.btnStart);
        Button btnWait = (Button) findViewById(R.id.btnWait);
        Button btnRest = (Button) findViewById(R.id.btnReset);


        Message message = new Message();
        //给消息设置一个标识
        message.what = start;
        message.what = wait;
        message.what = reset;


        btnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(flag ==2) {
                    flag = 0;
                }


                if (flag == 0) {
                    if (editText.getText().toString().equals(""))
                    {
                        Toast.makeText(MainActivity.this,"请输入倒计时秒数",Toast.LENGTH_SHORT).show();
                    }else {
                        num = Integer.parseInt(editText.getText().toString());
                    }
                } else if (flag == 1) {
                    num_wait = Integer.parseInt(textView.getText().toString());
                }
                if (f_wait == 1) {
                    f_wait=0;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (num >= 0 && f_wait == 0 || num_wait > 0 && f_wait == 0) {
                            handler.sendEmptyMessage(start);
                            handler.postDelayed(this::run, 1000);
                        } else if (f_wait == 1){
                            num = -1;
                        }else{
                            MediaPlayer mp = new MediaPlayer();
                            try {
                                mp.setDataSource(MainActivity.this, RingtoneManager
                                        .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));//通知声音
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            try {
                                mp.prepare();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            mp.start();
                        }

                    }
                }).start();
            }
        });


        btnWait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                f_wait = 1;
                flag = 1;
                num_wait = Integer.parseInt(textView.getText().toString());
                Log.d("msg", String.valueOf(num_wait));
                if (num_wait > 0) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            handler.sendEmptyMessage(wait);
                        }
                    }).start();
                }
            }
        });


        btnRest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        flag =2;
                        handler.sendEmptyMessage(start);
                    }
                }).start();
            }
        });

    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onStop() {
        super.onStop();
        sendNotification();
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public void sendNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        String id = "channel";
        String description = "clock";
        int importance = NotificationManager.IMPORTANCE_LOW;
        Intent intent = new Intent();
        PendingIntent pendingIntent =
                PendingIntent.getActivity(this, 0, intent, 0);
        NotificationChannel channel = new NotificationChannel(id, description, importance);
        channel.enableLights(true);
        channel.enableVibration(true);//
        manager.createNotificationChannel(channel);
        @SuppressLint("WrongConstant")
        Notification notification = new Notification.Builder(MainActivity.this, id)
                .setContentTitle("定时任务")//设置标题
                .setContentText("在后台计时")//设置内容
                .setWhen(System.currentTimeMillis())//设置通知的时间
                .setSmallIcon(R.drawable.clock2)//设置小图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.clock1))//设置大图标
                .setContentIntent(pendingIntent)//延迟处理的意图，当点击通知时
                .setAutoCancel(false)//设置当用户点击面板时通知自动取消
                .setDefaults(NotificationCompat.DEFAULT_ALL)//使用默认的通知选项
                .setPriority(NotificationCompat.PRIORITY_MAX)//设置通知的优先级
                .build();
        manager.notify(1, notification);
    }


}